package com.bridgeintelligent.tag.webserver.logs;

import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.utils.SecurityHelper;
import com.bridgeintelligent.tag.webserver.logs.entity.OperationLog;
import com.bridgeintelligent.tag.webserver.logs.mapper.OperationLogMapper;
import com.wayneleo.quickstart.framework.IDGenerator;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

@Component
@AllArgsConstructor
public class LogsInterceptor implements HandlerInterceptor, WebMvcConfigurer {
    private OperationLogMapper operationLogMapper;
    @Override
    public void addInterceptors( InterceptorRegistry registry ) {
        registry.addInterceptor( this ).addPathPatterns( "/api/**" );
    }

    @Override
    public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) throws Exception {
        OperationLog log = new OperationLog()
                .setId( IDGenerator.gen() )
                .setUsername( getUsername() )
                .setDatetime( DateHelper.currentDateTime() )
                .setOperation( getOperationName( handler ) )
                .setUrl( request.getRequestURL().toString() )
                .setMethod( request.getMethod() )
                .setParams( SerializationUtils.serialize( (Serializable) request.getParameterMap() ) );
        operationLogMapper.save( log );
    }

    private String getUsername() {
        String username = "未知用户";
        User user = SecurityHelper.currentUser();
        username = user.getUsername();
        return username;
    }

    private String getOperationName( Object handler ) {
        String operation = "未知操作";
        if ( !( handler instanceof HandlerMethod ) ) { return operation; }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if ( !handlerMethod.hasMethodAnnotation( ApiOperation.class ) ) { return operation; }
        ApiOperation api = handlerMethod.getMethodAnnotation( ApiOperation.class );
        operation = api.value();
        return operation;
    }
}
